<?php

namespace Managers\Reader;

/**
 * Класс для преобразование pdf в рисунки
 */
class PDF
{
    private $file;

    /**
     * @var \Catalog\PdfFile
     */
    private $pdfFile;

    private $density;

    private $uploadDir;

    private $saveDir;

    public function __construct(\Catalog\PdfFile $pdfFile)
    {

        $this->pdfFile = $pdfFile;
        $this->density = \Zend_Registry::get('config')->pdf->image->density;
        if (!extension_loaded('imagick')) {
            throw new \Exception('Image magick is not installed.');
        }
        $uploadDir = \Zend_Registry::get('config')->pdf->image->dir;
        $this->uploadDir = dirname(APPLICATION_PATH) . $uploadDir;
        $pdfDir = \Zend_Registry::get('config')->pdf->upload->dir;
        $this->file = dirname(APPLICATION_PATH) . $pdfDir . $pdfFile->getUrl();
    }

    public function getImages()
    {
        \Lib_Log::toFile('im here', 'upload', \Zend_Log::ERR);
        $images = array();
        $pagesCount = $this->getPagesCount();
        $this->saveDir = $this->uploadDir . $this->pdfFile->getId() . DIRECTORY_SEPARATOR;
        @mkdir($this->saveDir);
        for ($i = 0; $i < $pagesCount; $i++) {

            \Lib_Log::toFile($i, 'upload', \Zend_Log::ERR);
            $im = new \Imagick();
            $im->setResolution($this->density, $this->density);
            $im->readImage($this->file . "[$i]");
//            $params = $im->getImageGeometry();
            $im->setImageFormat('jpeg');
            $im->setImageCompressionQuality(80);

            $bigFileName = $this->getImageFile($i, 'b');
            $im->resizeimage(1200, 1800, \Imagick::FILTER_LANCZOS,1);
            $im->writeimage($bigFileName);
            \Lib_Log::toFile('save big', 'upload', \Zend_Log::ERR);
//            $im->destroy();
//
//
            //GRABLI - nado budet normalno cherez rezolution reshit
//            $im = new \Imagick();
//            $im->setResolution($this->density, $this->density);
//            $im->readImage($this->file . "[$i]");
            $im->resizeimage(900, 1350, \Imagick::FILTER_LANCZOS,1);
            $midlFileName = $this->getImageFile($i, 'm');
            $im->writeimage($midlFileName);
            \Lib_Log::toFile('save small', 'upload', \Zend_Log::ERR);
//            $im->destroy();



//            $im = new \Imagick();
//            $im->setResolution($this->density, $this->density);
//            $im->readImage($this->file . "[$i]");
            $im->resizeimage(600, 900, \Imagick::FILTER_LANCZOS,1);
//            $im->adaptiveresizeimage(600, 900);
//            $im->setImageFormat('jpeg');
//            $im->scaleImage($params['width'] / 2, $params['height'] / 2, true);
            $fileName = $this->getImageFile($i, '');
            $im->writeimage($fileName);
            \Lib_Log::toFile('save thumb', 'upload', \Zend_Log::ERR);
            $im->destroy();

            $images[] = preg_replace('/.*\/public/', '', $fileName);
        }
        return $images;
    }

    private function getImageFile($page, $suffix = false)
    {
        $filePath = $this->saveDir . $page . $suffix . '.jpg';
        return $filePath;
    }

    private function getPagesCount()
    {
        /**
         * VERY HARD CODED.
         * DON"T TRY THIS AT HOME;
         */
        return 45;

        $stream = @fopen($this->file, "r");
        $PDFContent = @fread($stream, filesize($this->file));
        if (!$stream || !$PDFContent)
            return false;

        $firstValue = 0;
        $secondValue = 0;
        if (preg_match("/\/N\s+([0-9]+)/", $PDFContent, $matches)) {
            $firstValue = $matches[1];
        }

        if (preg_match_all("/\/Count\s+([0-9]+)/s", $PDFContent, $matches)) {
            $secondValue = max($matches[1]);
        }
        return (($secondValue != 0) ? $secondValue : max($firstValue, $secondValue));
    }
}
